package com.service.admin.otc.controller;

import com.google.common.collect.Lists;
import com.service.admin.member.service.MemberStoreService;
import com.service.admin.support.MemberStoreLockUtils;
import com.service.admin.support.OtcOrderLockUtils;
import com.service.core.rest.BaseController;
import com.service.core.rest.response.*;
import com.service.admin.framework.log.RequestLog;
import com.service.admin.otc.controller.req.OtcOrderPageReq;
import com.service.admin.otc.service.OtcOrderService;
import com.service.dao.model.MemberStore;
import com.service.dao.model.OtcOrder;
import org.redisson.RedissonRedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/otc-order")
public class OtcOrderController extends BaseController {

    @Autowired
    private OtcOrderService otcOrderService;
    @Autowired
    private MemberStoreService memberStoreService;
    @Autowired
    private OtcOrderLockUtils lockUtils;

    @RequestLog("OTC交易分页查询")
    @PostMapping("/page")
    public PageResponse page(@RequestBody OtcOrderPageReq pageRequest ){
        return successQueryPageResponse(otcOrderService.pageOrder(pageRequest));
    }

    @GetMapping("/trade-detail/{otcId}")
    public MultiResponse detail(@PathVariable Integer otcId){
        return successQueryMultiResponse(otcOrderService.getOtcOrderTradeDetail(otcId));
    }

    @PostMapping("/cancel/{orderId}")
    public BaseResponse cancel(@PathVariable Integer orderId){

        OtcOrder order = otcOrderService.getById(orderId);
        List<String> lockKey = Lists.newArrayList();
        lockKey.add(OtcOrderLockUtils.buildOrderKey(order.getOtcNo()));
        List<MemberStore> storeList = Lists.newArrayList(
                memberStoreService.getMemberStore(order.getMemberId(), order.getTradeCoinsName()),
                memberStoreService.getMemberStore(order.getMemberId(), order.getCoinsName())
        );
        lockKey.addAll(MemberStoreLockUtils.buildStoreKey2List(storeList));
        RedissonRedLock redLock = lockUtils.getRedLock(lockKey);
        if (lockUtils.redLockTryLock(redLock)) {
            try {
                otcOrderService.cancelOrder(orderId);
            } finally {
                redLock.unlock();
            }
        }
        return successSaveBaseResponse();
    }
}
